package com.liuzhilin.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.liuzhilin.domain.Message;
import com.liuzhilin.service.ManagerService;
import com.liuzhilin.util.Response;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/managerLog")
public class ManagerLog extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应类型为 JSON
        Response.setCorsHeaders(response);
        response.setCharacterEncoding("UTF-8");

        // 设置响应内容类型为 JSON
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        // 调用服务层获取操作日志
        List<Message> logs = ManagerService.getOperationLogs();

        // 将日志信息转换为 JSON 格式，并返回给客户端
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            objectMapper.writeValue(out, logs);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.print("{\"message\": \"服务器错误\"}");
            e.printStackTrace();
        }
    }


    @Override
    public void doOptions(HttpServletRequest request, HttpServletResponse response) {
        Response.setCorsHeaders(response);
        response.setStatus(HttpServletResponse.SC_OK);
    }
}